<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think;

/**
 * ThinkPHP 控制器基类 抽象类
 */
class Weixin {

    /**
     * 视图实例对象
     * @var view
     * @access protected
     */    
    protected $view     =  null;

    /**
     * 控制器参数
     * @var config
     * @access protected
     */      
    public $config   =   array();
    public $appid='';
    public $appsecret='';
   /**
     * 架构函数 取得模板对象实例
     * @access public
     */
    public function __construct($wechat_appid,$wechat_secret) {


    $this->appid=$wechat_appid;
    $this->appsecret=$wechat_secret;
     define("TOKEN", "haotuoguan");
        // $wechatObj = new wechatCallbackapiTest();
        if (isset($_GET['echostr'])) {
            $this->valid();
        }else{
            $this->responseMsg();
           @ $this->receiveEvent($object);
        }

        $this->weixinauth();


    }
	    /*
     * 微信推广部分
     */
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }
    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    public function get_user_info($openid)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->https_request($url);
        return json_decode($res, true);
    }
    public function weixinauth(){
<<<<<<< Updated upstream
=======
       /* $appid = "wx341aadb59aac9389";
        $appsecret = "bd60468190f20a6c05072f8c787207c5";
        if($appid){
            $this->appid = $appid;
        }
        if($appsecret){
            $this->appsecret = $appsecret;
        }*/


>>>>>>> Stashed changes
        $this->lasttime = 1395049256;
        $this->access_token = "";
        $redis=getRedis();
       if(empty($redis->get('htg_access_token'))||time()-$redis->get('htg_time')>3600){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $res = $this->https_request($url);
            $result = json_decode($res, true);

            $this->access_token = $result["access_token"];
           // S('data',$this->access_token,600);
            $redis->set('htg_access_token',$this->access_token);
            $redis->set('htg_time',time());
        }else{
            $this->access_token = $redis->get('htg_access_token');
        }
    }
    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function dowmloadImageFromWeixin($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $package= curl_exec($curl);
        $httpinfo=curl_getinfo($curl);
        curl_close($curl);
        return array_merge(array('body'=>$package),array('header'=>$httpinfo));

    }
    //
    public function responseMsg()
    {
      //  print "欢迎关注";
      //  exit;
        //get post data, May be due to the different environments
        $postStr = @$GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
           // libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
           // var_dump($postObj);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
           $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";
//            $redis=getRedis();
//            $tokens=$redis->get('htg_access_token');
            if(!empty( $keyword ))
            {   //echo '122123'.$postObj->MsgType;

                    $msgType = "text";
                    $contentStr = "欢迎使用好托管家长端";
                  $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,$contentStr);
            
                    echo $resultStr;


            }

        }else {
          //  echo "";
          //  exit;
        }

    }
    private function receiveEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
            case "subscribe":
                $contentStr = "欢迎关注方倍工作室 ";
                if (isset($object->EventKey)){
                    $contentStr = "关注二维码场景 ".$object->EventKey;
                }
                break;
            case "SCAN":
                $contentStr = "扫描 ".$object->EventKey;
                //要实现统计分析，则需要扫描事件写入数据库，这里可以记录 EventKey及用户OpenID，扫描时间
                break;
            default:
                break;

        }
        $resultStr = $this->transmitText($object, $contentStr);
        //echo "欢迎关注";
        return $resultStr;

    }
    private function transmitText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }
}
